package com.jeesite.modules.sys.wx.qy.util;

import com.github.sd4324530.fastweixin.company.api.QYOauthAPI;
import com.github.sd4324530.fastweixin.company.api.QYUserAPI;
import com.github.sd4324530.fastweixin.company.api.config.QYAPIConfig;
import com.github.sd4324530.fastweixin.company.api.entity.QYUser;
import com.github.sd4324530.fastweixin.company.api.enums.QYResultType;
import com.github.sd4324530.fastweixin.company.api.response.GetOauthUserInfoResponse;
import com.github.sd4324530.fastweixin.company.api.response.GetQYUserInfo4DepartmentResponse;
import com.github.sd4324530.fastweixin.company.api.response.GetQYUserInfoResponse;
import com.jeesite.common.config.Global;
import com.jeesite.common.web.CookieUtils;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.wx.qy.py.WeixinJSSDKSignUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
@Lazy(false)
//@PropertySource("config/qy.properties")
public class QyConfigUtil {

    public static QYAPIConfig apiConfig;

    //获取通讯录的apiConfig
    public static QYAPIConfig txApiConfig;

//
//    @Value("${corpId}")
//    public void setCorpId(String corpId) {
//        QyConfigUtil.corpId = corpId;
//    }
//
//    @Value("${agentId}")
//    public void setAgentId(String agentId) {
//        QyConfigUtil.agentId = agentId;
//    }
//
//    @Value("${corpSecret}")
//    public void setCorpSecret(String corpSecret) {
//        QyConfigUtil.corpSecret = corpSecret;
//    }
//
//    @Value("${txSecret}")
//    public void setTxSecret(String txSecret) {
//        QyConfigUtil.txSecret = txSecret;
//    }


    public static QYAPIConfig getQYAPIConfig() {
        if (apiConfig == null) {
            apiConfig = new QYAPIConfig(Global.getConfig("ajz.qy.corpId"), Global.getConfig("ajz.qy.corpSecret"), true);
        }
        return apiConfig;

    }

    public static QYAPIConfig getTXQYAPIConfig() {
        if (txApiConfig == null) {
            txApiConfig = new QYAPIConfig(Global.getConfig("ajz.qy.corpId"),  Global.getConfig("ajz.qy.txSecret"));
        }
        return txApiConfig;

    }

    public static QYUserAPI getQyUserAPI() {
        QYAPIConfig apiConfig = getQYAPIConfig();
        QYUserAPI qyUserAPI = new QYUserAPI(apiConfig);
        return qyUserAPI;
    }


    public static QYOauthAPI getQYOauthAPI() {
        QYAPIConfig apiConfig = getQYAPIConfig();
        QYOauthAPI qyOauthAPI = new QYOauthAPI(apiConfig);
        return qyOauthAPI;
    }

    //获取accessToken
    public static String getAccessToken() {
        QYAPIConfig apiConfig = getQYAPIConfig();
        String token = apiConfig.getAccessToken();
        return token;
    }


    //创建用户
    public static QYResultType createUser(User user) {
        Employee employee = (Employee) user.getRefObj();
        String department = employee.getOffice().getViewCode();


        Integer[] a = new Integer[1];
        a[0] = Integer.parseInt(department);

        //封装user
        QYUser qyUser = new QYUser();
        qyUser.setUserId(user.getLoginCode());
        qyUser.setName(user.getUserName());
        qyUser.setMobile(user.getMobile());
        qyUser.setDepartment(a);

        QYAPIConfig qyapiConfig = getTXQYAPIConfig();

        //获取api 并进行调取
        QYUserAPI qyUserAPI = new QYUserAPI(qyapiConfig);
        QYResultType qyResultType = qyUserAPI.create(qyUser);

        return qyResultType;
    }

//    更新企业微信用户信息
    public static QYResultType updateUser(User user) {
        QYUser qyUser = new QYUser();

        Employee employee = (Employee) user.getRefObj();
        String department = employee.getOffice().getViewCode();

        Integer[] a = new Integer[1];
        a[0] = Integer.parseInt(department);
        qyUser.setUserId(user.getLoginCode());
        qyUser.setName(user.getUserName());
        qyUser.setMobile(user.getMobile());
        qyUser.setDepartment(a);


        QYAPIConfig qyapiConfig = getTXQYAPIConfig();

        //获取api 并进行调取
        QYUserAPI qyUserAPI = new QYUserAPI(qyapiConfig);
        QYResultType qyResultType = qyUserAPI.update(qyUser);
        return qyResultType;
    }

//    获取企业微信用户
    public static GetQYUserInfoResponse getUser(User user){
        QYAPIConfig qyapiConfig = getTXQYAPIConfig();
        QYUserAPI qyUserAPI = new QYUserAPI(qyapiConfig);
        return  qyUserAPI.get(user.getLoginCode());
    }

    public static String getUserId(HttpServletRequest request, HttpServletResponse response) {
        //通过code值获取openid
        QYUserAPI oauthAPI = QyConfigUtil.getQyUserAPI();

        String code = request.getParameter("code");
        String userId = CookieUtils.getCookie(request, "userId");
        //为空代表从原地址进来,
        if (StringUtils.isEmpty(userId)) {
            if (StringUtils.isEmpty(code)) {
                userId = request.getParameter("userId");
                if (!StringUtils.isEmpty(userId)) {
                    CookieUtils.setCookie(response, "userId", userId);
                }
            } else { //不为空说明 重定向 网页授权
                GetOauthUserInfoResponse userInfoResponse = oauthAPI.getOauthUserInfo(code);
                userId = userInfoResponse != null ? userInfoResponse.getUserid() : "";
                CookieUtils.setCookie(response, "userId", userId);
            }
        }
        return userId;
    }

    //获得微信jssdk签名等
    public static void getJSSDKSign(HttpServletRequest request,Model model){
        String queryString = request.getQueryString();
        QYAPIConfig qyapiConfig = QyConfigUtil.getQYAPIConfig();
        String jsapi_ticket = qyapiConfig.getJsApiTicket();
        String url2 = "http://" + request.getServerName() // 服务器地址
                + request.getContextPath() // 项目名称
                + request.getServletPath(); // 请求页面或其他地址
        if (queryString != null) {
            url2 += "?" + queryString;
        }
        Map<String, String> sign = WeixinJSSDKSignUtil.sign(jsapi_ticket, url2);

        model.addAttribute("appId", QyConfigUtil.apiConfig.getCorpid());
        model.addAttribute("nonceStr", sign.get("nonceStr"));
        model.addAttribute("timestamp", sign.get("timestamp"));
        model.addAttribute("signature", sign.get("signature"));
    }

    public static Map<String,QYUser> tel = new HashMap<String,QYUser>();

    //通过部门id获取用户列表
    public static GetQYUserInfo4DepartmentResponse getUserList(User user){

//        如果需要根据用户的部门id查询开放下面注释
        Integer department = 1;//默认查询全部企业微信信息
        if(user!=null){//查询某个部门下的企业微信信息
            Employee employee = (Employee) user.getRefObj();
            department = Integer.parseInt(employee.getOffice().getViewCode());
        }

        QYAPIConfig qyapiConfig = getTXQYAPIConfig();

        //获取api 并进行调取
        QYUserAPI qyUserAPI = new QYUserAPI(qyapiConfig);
        GetQYUserInfo4DepartmentResponse userList = qyUserAPI.getList(department,false,0);

        if(tel.size()!=userList.userList.size()){
            tel = new HashMap<String,QYUser>(userList.userList.size());
            for(QYUser qyUser : userList.userList){
                tel.put(qyUser.getMobile(),qyUser);
            }
        }

        return userList;

    }

    //通过仅通过部门id获取用户列表
    public static GetQYUserInfo4DepartmentResponse getUserListByDepartment(String officeCode){
        Integer department ;
        try{
            department = Integer.parseInt(officeCode);
        }catch (Exception e){
            department = 1;
        }

        QYAPIConfig qyapiConfig = getTXQYAPIConfig();

        //获取api 并进行调取
        QYUserAPI qyUserAPI = new QYUserAPI(qyapiConfig);
        GetQYUserInfo4DepartmentResponse userList = qyUserAPI.getList(department,false,0);

        if(tel.size()!=userList.userList.size()){
            tel = new HashMap<String,QYUser>(userList.userList.size());
            for(QYUser qyUser : userList.userList){
                tel.put(qyUser.getMobile(),qyUser);
            }
        }

        return userList;

    }



}